package api

import (
	"net/http"
	"portal_api/global"
	"portal_api/models/response"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func HandleValidatorError(c *gin.Context, err error) {
	zap.L().Error("参数错误", zap.Error(err))
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		c.JSON(http.StatusBadRequest, response.Response{
			Code:    http.StatusBadRequest,
			Message: err.Error(),
		})
		return
	}
	c.JSON(http.StatusBadRequest, gin.H{
		"code":    http.StatusBadRequest,
		"message": RemoveTopStruct(errs.Translate(global.Trans)),
	})
}

func HandleGRPCError(c *gin.Context, err error) {
	if e, ok := status.FromError(err); ok {
		switch e.Code() {
		case codes.NotFound:
			zap.L().Error("未找到用户", zap.Error(err))
			c.JSON(http.StatusNotFound, response.Response{
				Code:    http.StatusNotFound,
				Message: "未找到用户",
			})
		case codes.Internal:
			zap.L().Error("内部错误", zap.Error(err))
			c.JSON(http.StatusInternalServerError, response.Response{
				Code:    http.StatusInternalServerError,
				Message: "内部错误",
			})
		case codes.InvalidArgument:
			zap.L().Error("参数错误", zap.Error(err))
			c.JSON(http.StatusBadRequest, response.Response{
				Code:    http.StatusBadRequest,
				Message: "参数错误",
			})
		case codes.Unavailable:
			zap.L().Error("服务不可用", zap.Error(err))
			c.JSON(
				http.StatusServiceUnavailable,
				response.Response{
					Code:    http.StatusServiceUnavailable,
					Message: "服务不可用",
				},
			)
		default:
			zap.L().Error("未知错误", zap.Error(err))
			c.JSON(http.StatusInternalServerError,
				response.Response{
					Code:    http.StatusInternalServerError,
					Message: "未知错误",
				})
		}
		return
	}
	zap.L().Error("未知错误", zap.Error(err))
	c.JSON(http.StatusInternalServerError, response.Response{
		Code:    http.StatusInternalServerError,
		Message: "未知错误",
	})
}

// 去除 xxxx.password: 的.前面的信息
func RemoveTopStruct(fields map[string]string) map[string]string {
	rst := make(map[string]string, len(fields))
	for field, err := range fields {
		rst[field[strings.Index(field, ".")+1:]] = err
	}
	return rst
}
